package com.xb.cloud.common.util;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.springframework.util.Base64Utils;

public class RSAUtils {

	private static final int KEY_SIZE = 1024;

	/**
	 * 私钥
	 */
	private static final String PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKlHnXpon4j/8LFRb/fu8v/+ZznWXJpQDSndWOzsuVm5HF4SsQBLvq2IvDptqmMO3cRfWQjhJh0wqL+i+tH3Opn0iPPmU7sfLvVKzaALsDJAFJRM77/IH4qgFS4ODzX9NpogrBYvUX3vII/ipjDxOzRI1+Aary16e4kAzaRlB39zAgMBAAECgYBWtnOpt5w5TnnaKxBDHejmT0hLbU5EUctcbaFWxDByEIvCeKqoryQ+unNJLtIAKiZZqEnwbXzbqQhYGkGHerBOQucrpOzY3mGLlsYJtpHH0LuzYDh8Sqo5oFMQypIq8pBHzxu/AJDBFUz1Z2xmA7N1VPRFyafHv1Z/s6fH7PQ5AQJBAPQIhY7k55TYb51HVlaFvHdirA5t4VDdbUhh95yhCcous4O7XssgDchAp/b7IqoSNyg2eloq2und0guOYOmspvMCQQCxlKxCy1G0ZdWtBixzfXwppqDI9ZOO4tpgs11Co8rIsoV9dRyYqrvpfO1yPTpmK4FGxuEgq/cQZ4yuKjpJkOWBAkEAmzT4TQPFTmPByVRf0zPHxF6bc6nrDhVmtgypAZNiuJavUe9PwP0oBt8odOsRBv4C2q6bbtGm3etY9kSd2sEWhQJADZEtRAEioeSx2YFCPiSVKt13JUNV3bHJO2AYvPGkmYbCGh6ra6KHrsQDpBm3b3zdaJnjM0rQGmm+3sONJneygQJBAJGf+RVDdolEkDd2AkCyg/7y8pYz1CxQ4TAwk9fn96AbVfGnc1xun7AkhTh7Uw+2ked199ZGsJy8III3qDeIpIA=";

	/**
	 * 公钥
	 */
	private static final String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCpR516aJ+I//CxUW/37vL//mc51lyaUA0p3Vjs7LlZuRxeErEAS76tiLw6bapjDt3EX1kI4SYdMKi/ovrR9zqZ9Ijz5lO7Hy71Ss2gC7AyQBSUTO+/yB+KoBUuDg81/TaaIKwWL1F97yCP4qYw8Ts0SNfgGq8tenuJAM2kZQd/cwIDAQAB";

	public static final int MAX_ENCRYPT_BLOCK = 127;

	public static final int MAX_DECRYPT_BLOCK = 128;

	public static final String KEY_ALGORITHM = "RSA";

	public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

	/**
	 * RSA签名
	 * 
	 * @param data
	 *            RSA签名
	 * @param privateKey
	 * @return
	 * @throws Exception
	 */
	public static String sign(String content, String privateKey, String input_charset) {
		byte[] sign = null;
		try {
			byte[] data = content.getBytes(input_charset);
			byte[] keyBytes = Base64.getEncoder().encode(privateKey.getBytes());
			PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
			KeyFactory keyFactory = KeyFactory.getInstance("RSA");
			PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
			Signature signature = Signature.getInstance("MD5withRSA");
			signature.initSign(privateK);
			signature.update(data);
			sign = signature.sign();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Base64Utils.encodeToString(sign);
	}

	/**
	 * 用私钥对信息生成数字签名
	 * 
	 * @param data
	 *            已加密数据
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * @return
	 */
	public static String sign(byte[] data, String privateKey) throws Exception {
		byte[] keyBytes = Base64Utils.decodeFromString(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
		signature.initSign(privateK);
		signature.update(data);
		return Base64Utils.encodeToString(signature.sign());
	}

	/**
	 * 校验数字签名
	 * 
	 * @param data
	 *            已加密数据
	 * @param publicKey
	 *            公钥(BASE64编码)
	 * @param sign
	 *            数字签名
	 * @return
	 * 
	 */
	public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
		byte[] keyBytes = Base64Utils.decodeFromString(publicKey);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PublicKey publicK = keyFactory.generatePublic(keySpec);
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
		signature.initVerify(publicK);
		signature.update(data);
		return signature.verify(Base64Utils.decodeFromString(sign));
	}

	/**
	 * RSA公钥加密
	 * 
	 * @param content
	 *            待加密的明文
	 * @param publicKey
	 *            公钥
	 * @param input_charset
	 *            编码格式
	 * @return 加密后的密文
	 */
	public static byte[] encrypt(byte[] data, String publicKey) throws Exception {

		byte[] keyBytes = Base64Utils.decodeFromString(publicKey);

		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");

		Key publicK = keyFactory.generatePublic(x509KeySpec);
		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicK);
		int length = data.length;

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] bytes;
		int i = 0;
		while (length - offSet > 0) {
			if (length - offSet > MAX_ENCRYPT_BLOCK) {
				bytes = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				bytes = cipher.doFinal(data, offSet, length - offSet);
			}

			out.write(bytes, 0, bytes.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();

		return encryptedData;
	}

	/**
	 * RSA私钥解密
	 * 
	 * @param content
	 *            待解密的密文
	 * @param privateKey
	 *            私钥
	 * @param input_charset
	 *            编码格式
	 * @return 解密后的明文
	 */
	public static byte[] decrypt(byte[] data, String privateKey) throws Exception {

		byte[] keyBytes = Base64Utils.decodeFromString(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);

		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateK);
		int length = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (length - offSet > 0) {
			if (length - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, length - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();

		return decryptedData;
	}

	/**
	 * 生成密钥对
	 * 
	 * @return
	 * @throws Exception
	 */
	private static Map<String, Object> generateKeyPair() throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();

		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
		keyPairGen.initialize(KEY_SIZE);
		KeyPair keyPair = keyPairGen.generateKeyPair();

		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

		map.put("publicKey", publicKey);
		map.put("privateKey", privateKey);

		return map;
	}

	public static String encryptStr(String password) throws Exception {
		byte[] encodedData = RSAUtils.encrypt(password.getBytes(), PUBLIC_KEY);
		return Base64Utils.encodeToString(encodedData);
	}

	public static String decryptStr(String codeDate) throws Exception {
		byte[] deDate = Base64Utils.decodeFromString(codeDate);
		byte[] decodedData = RSAUtils.decrypt(deDate, PRIVATE_KEY);
		return new String(decodedData, "UTF-8");
	}

	public static void main(String[] args) throws Exception {
		String content = "123456";
		String stdd = RSAUtils.encryptStr(content);
		System.out.println(stdd);
		String straaa = RSAUtils.decryptStr(stdd);
		System.out.println(straaa);
	}
}
